from time import sleep
from tenacity import retry, stop_after_attempt, wait_fixed

def click_element(d, by, value):
    element = d(**{by: value})
    assert element.exists, f"找不到控件 {value}"
    element.click()
    print(f"✅ 点击控件 '{value}'")


def scroll_and_click(d, text, max_swipes=10):
    for _ in range(max_swipes):
        if d(text=text).exists:
            d(text=text).click()
            print(f"✅ 成功点击 '{text}'")
            return True
        d.swipe(0.5, 0.8, 0.5, 0.2)
        sleep(1)
    raise AssertionError(f"❌ 超过最大滑动次数仍未找到 '{text}'")


def verify_text_exists(d, text, timeout=5):
    assert d(text=text).wait(timeout=timeout), f"❌ 未找到文本 '{text}'"
    print(f"✅ 找到文本 '{text}'")




def take_screenshot(d, name="error"):
    filename = f"results/screenshots/{name}_{time.strftime('%Y%m%d_%H%M%S')}.png"
    d.screenshot(filename)
    print(f"📸 截图已保存至 {filename}")


@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))
def retry_click_element(d, by, value):
    element = d(**{by: value})
    assert element.exists, f"找不到控件 {value}"
    element.click()
    print(f"✅ 成功点击 '{value}'")
















